package com.hitqz.robot.biz.flow.component.patrol;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hitqz.robot.api.business.entity.CvdStoveEntity;
import com.hitqz.robot.api.business.entity.PatrolResultEntity;
import com.hitqz.robot.api.business.model.dto.FlowContextDto;
import com.hitqz.robot.api.business.model.dto.FlowPatrolPreAndEndTicketsDto;
import com.hitqz.robot.api.common.entity.*;
import com.hitqz.robot.biz.config.CvdProperties;
import com.hitqz.robot.biz.service.*;
import com.hitqz.robot.common.core.jackson.RobotJavaTimeModule;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import com.yomahub.liteflow.core.NodeComponent;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;

@Slf4j
@LiteflowComponent(value = "GenerateResults", name = "[巡检]生成检测报告模板")
@AllArgsConstructor
public class GenerateResults extends NodeComponent {

    private final PatrolResultService patrolResultService;

    private final PatrolItemService patrolItemService;

    private final PatrolObjectService patrolObjectService;

    private final PatrolPosPoseGroupService patrolPosPoseGroupService;

    private final PatrolDevService patrolDevService;

    private final ExecutorService customThreadPool;

    private final CvdProperties cvdProperties;

    private final RestTemplate restTemplate;

    private static final ObjectMapper objectMapper = new ObjectMapper()
            .registerModule(new RobotJavaTimeModule());
    @Override
    public void process() throws Exception {
        FlowContextDto dto = this.getRequestData();
        TicketsTask task = dto.getTicketsTask();
        log.info("任务数据 {}", task.getParseOrderParams());
        FlowPatrolPreAndEndTicketsDto params = JSONObject.parseObject(task.getParseOrderParams(), FlowPatrolPreAndEndTicketsDto.class);
        log.info("{} ---params: {}", task.getParseOrderParams(), JSONObject.toJSONString(params));
        if (StrUtil.isBlank(params.getPatrolItemIds())) {
            log.warn("没有检测项信息,不执行");
            return;
        }
        List<PatrolResultEntity> list = patrolResultService.list(Wrappers.<PatrolResultEntity>lambdaQuery()
                .eq(PatrolResultEntity::getTicketsId, dto.getTickets().getId()));
        if (!list.isEmpty()) {
            log.info("已有检测结果模版,不再创建");
            return;
        }
        List<CvdStoveEntity> stoveList = this.getStoveList();
        Map<String, CvdStoveEntity> stoveMap = stoveList.stream().collect(
                Collectors.toMap(CvdStoveEntity::getName, v -> v));
        List<PatrolResultEntity> resultList = new ArrayList<>();
        String[] items = params.getPatrolItemIds().split(",");
        for (String itemId : items) {
            if (StrUtil.isBlank(itemId)) {
                continue;
            }
            try {
                PatrolResultEntity patrolResult = new PatrolResultEntity();
                patrolResult.setTicketsId(dto.getTickets().getId().intValue());
                PatrolItem item = patrolItemService.getById(itemId);
                patrolResult.setItemName(item.getName());
                patrolResult.setItemId(item.getId().intValue());
                PatrolObject patrolObject = patrolObjectService.getById(item.getPatrolObjectId());
                patrolResult.setPatrolObjectId(patrolObject.getId().intValue());
                patrolResult.setCreateTime(new Date());
                patrolResult.setStatus(0);
                patrolResult.setUploadStatus(0);
                PatrolPosPoseGroup posPoseGroup = patrolPosPoseGroupService.getById(item.getPatrolPosPoseGroupId());
                PatrolDev dev = patrolDevService.getById(posPoseGroup.getDevId());
                String devName = dev.getName();
                patrolResult.setDevName(devName);
                //设置炉子信息
                if (stoveMap.containsKey(devName)) {
                    CvdStoveEntity stove = stoveMap.get(devName);
                    patrolResult.setStoveName(stove.getName());
                    patrolResult.setStoveStatus(stove.getStatus());
                    patrolResult.setStoveStartTime(stove.getStartTime());
                    patrolResult.setStoveEndTime(stove.getEndTime());
                    patrolResult.setStoveProductCycle(stove.getProductCycle());
                    patrolResult.setStoveLastRunningTime(stove.getLastRunningTime());
                    patrolResult.setStoveProductName(stove.getProductName());
                    patrolResult.setStoveProductCode(stove.getProductCode());
                    patrolResult.setStoveExportType(stove.getExportType());
                    patrolResult.setStoveExecNo(stove.getExecNo());
                }
                PatrolDev room = patrolDevService.getById(dev.getParentId());
                patrolResult.setRoomName(room.getName());
                resultList.add(patrolResult);
                customThreadPool.submit(() -> {
                    patrolResultService.upload2Server(patrolResult);
                });
            } catch (Exception e) {
                log.error("创建报告明细{}错误{}", itemId, e.getMessage(),e);
            }
        }
        if (!resultList.isEmpty()) {
            patrolResultService.saveBatch(resultList);
        }

    }

    private List<CvdStoveEntity> getStoveList() {
        //请求炉子信息
        StringBuilder urlBuilder = new StringBuilder();
        urlBuilder.append("http://").append(cvdProperties.getServerIpAddr()).append(":").append(cvdProperties.getServerHttpPort()).append("/admin/cvdStove/list");
        ResponseEntity<String> rawResponse = restTemplate.exchange(
                urlBuilder.toString(), HttpMethod.GET,
                new HttpEntity<>(new HttpHeaders()),
                String.class);
        String jsonStr = rawResponse.getBody();
        log.info("Received raw response: {}", jsonStr);
        try {
            // 使用Jackson将JSON字符串转换为List<CvdStoveEntity>
            JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, CvdStoveEntity.class);
            List<CvdStoveEntity> stoveList = objectMapper.readValue(jsonStr, javaType);
            return Optional.ofNullable(stoveList).orElse(new ArrayList<>());
        } catch (Exception e) {
            log.error("Failed to parse JSON to List<CvdStoveEntity>, raw data: {}",jsonStr, e);
            return new ArrayList<>();
        }
    }

}